#include "mqtthandler.h"
#include <QTimer>
#include <qmqtt_client.h>
#include <QJsonObject>
#include <QJsonDocument>
#include <QDateTime>
#include <QDebug>

// 修正主题定义：明确区分发送和接收主题
#define TOPIC_DATA_UP       "MQTT  rec"        // 发送数据主题
#define TOPIC_DATA_DOWN     "MQTT Examples"    // 接收数据主题
#define TOPIC_CTL_UP        "MQTT  rec"        // 发送控制主题
#define TOPIC_CTL_DOWN      "MQTT Examples"    // 接收控制主题
#define HEARTBEAT_INTERVAL  30000              // 心跳包间隔30秒

MqttHandler::MqttHandler(QObject *parent) : QObject(parent)
{
    client = new QMQTT::Client();
    client->setClientId("home-app");

    connect(client, SIGNAL(connected()), this, SLOT(doConnected()));
    connect(client, SIGNAL(disconnected()), this, SLOT(doDisconnected()));
    connect(client, SIGNAL(subscribed(QString, quint8)), this, SLOT(doSubscribed(QString, quint8)));
    connect(client, SIGNAL(received(QMQTT::Message)), this, SLOT(doDataReceived(QMQTT::Message)));
}

void MqttHandler::connectToHost()
{
    qDebug() << "尝试连接到MQTT服务器...";
    client->connectToHost();

    // 3秒后检测连接状态
    QTimer::singleShot(3000, this, SLOT(detectState()));
}

void MqttHandler::detectState()
{
    int state = client->connectionState();
    if(state != 2)  // 2表示已连接状态
    {
        qDebug() << "MQTT连接失败，当前状态:" << state;
        emit disconnectedSignal();
        emit deviceOfflineSignal();  // 发出设备离线信号
    } else {
        qDebug() << "MQTT连接检测成功";
    }
}

/**
 * @brief 连接成功后订阅接收主题
 */
void MqttHandler::doConnected()
{
    qDebug() << "MQTT连接成功，开始订阅接收主题";

    // 订阅设备上报主题
    client->subscribe(TOPIC_DATA_DOWN);

    emit connectedSignal();
}

// 断开连接槽函数
void MqttHandler::doDisconnected()
{
    qDebug() << "MQTT连接断开";

    emit disconnectedSignal();
    emit deviceOfflineSignal();  // 发出设备离线信号
}

void MqttHandler::doSubscribed(const QString& topic, const quint8 qos)
{
    qDebug() << "订阅成功, topic=" << topic << ", qos=" << qos;
}

void MqttHandler::doDataReceived(QMQTT::Message message)
{
    qDebug() << "接收到MQTT消息, topic=" << QString(message.topic());
    qDebug() << "payload=" << QString(message.payload());

    // 所有设备上报的消息都通过dataUpSignal发送
    if(message.topic() == TOPIC_DATA_DOWN){
        qDebug() << "设备数据上报主题";
        emit dataUpSignal(message.payload());
    }
}

quint16 MqttHandler::publish(const QMQTT::Message &message)
{
    qDebug() << "发布MQTT消息, topic:" << message.topic();
    return client->publish(message);
}

// 添加便捷的发送函数
quint16 MqttHandler::publishData(const QByteArray &data)
{
    QMQTT::Message message;
    message.setTopic(TOPIC_DATA_UP);
    message.setPayload(data);
    return publish(message);
}

quint16 MqttHandler::publishControl(const QByteArray &data)
{
    QMQTT::Message message;
    message.setTopic(TOPIC_CTL_UP);
    message.setPayload(data);
    return publish(message);
}
